<template>
  <nut-config-provider :theme="theme" :theme-vars="themeVars">
    <view :style="{backgroundColor: 'white',padding: themeVars.pagePadding,height: '100vh'}">
      <nut-form
          ref="formRef"
          :model-value="formData"
          :rules="formRules"
      >
        <nut-form-item label="发布类型" prop="productType">
          <nut-radio-group v-model="formData.productType" direction="horizontal">
            <nut-radio :label="item.dictValue" v-for="item in productTypeOptions">{{ item.dictLabel }}</nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="商品名称" prop="name">
          <nut-input
              v-model="formData.name"
              placeholder="请输入商品名称"
              type="text"

          />
        </nut-form-item>
        <nut-form-item label="商品分类" prop="threeLevelCategoryName">
          <nut-input
              v-model="formData.threeLevelCategoryName"
              placeholder="请输入商品分类"
              type="text"
              @click="visible=true"
          >
            <template #right>
              <IconFont size="10"
                        name="rect-right"></IconFont>
            </template>
          </nut-input>
        </nut-form-item>


        <nut-form-item label="商品价格" prop="price">
          <nut-input
              v-model="formData.price"
              placeholder="请输入商品价格"
              type="digit"

          />
        </nut-form-item>

        <nut-form-item label="商品规格" prop="specs">
          <nut-input
              v-model="formData.specs"
              placeholder="请输入商品规格"
              type="text"

          />
        </nut-form-item>

        <nut-form-item label="产品图片"
                       prop="productImg"
        >
          <nut-uploader
              v-model:file-list="formData.productImg"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="1"
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
                      const resData = JSON.parse(data.data)
                      fileItem.url = resData.data
                        console.log('success',data,fileItem)
                      }"
              @failure="({data,fileItem, option,responseText})=>{
                          const resData = JSON.parse(data.data)
                          Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
                      }"
          >
          </nut-uploader>
        </nut-form-item>
        <nut-form-item
            label="详情说明"
            prop="detailDesc"
        >
          <nut-textarea v-model="formData.detailDesc" placeholder="请输入详情说明" type="text"/>
        </nut-form-item>
        <nut-form-item label="图片说明"
                       prop="imgDesc"

        >
          <nut-uploader
              v-model:file-list="formData.imgDesc"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="9"
              multiple
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
                      const resData = JSON.parse(data.data)
                      fileItem.url = resData.data
                        console.log('success',data,fileItem)
                      }"
              @failure="({data,fileItem, option,responseText})=>{
                          const resData = JSON.parse(data.data)
                          Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
                      }"
          >
          </nut-uploader>
        </nut-form-item>

        <view style="display: flex;justify-content: center;margin: 20px 0">
          <nut-button color="#0073ff" style="width: 200px" @click="submit"> 保存</nut-button>
        </view>
      </nut-form>


      <nut-cascader
          v-model:visible="visible"
          v-model="formData.categoryArr"
          title="选择产品类型"
          text-key="name"
          value-key="id"
          children-key="children"
          :options="busiTypeList"
          @change="change"
      ></nut-cascader>
    </view>

  </nut-config-provider>
</template>

<script>
import {ref, toRaw} from 'vue';
import {IconFont} from '@nutui/icons-vue'
import {BankNoReg, IdNumReg, Phone1Reg} from "../../../utils/regUtils";

import useTheme from "../../../hooks/useTheme";
import Taro from "@tarojs/taro";
import {getDictList} from "../../../utils/dictUtils";
import {twProductCategoryPage} from "../../../api/productCategory";
import getBaseUrl from "../../../network/baseUrl";
import {Api} from "../../../api/dev";
import {cloneDeep} from "lodash";
import {twProductAudit, twProductMyDetail, twProductSubmitForm} from "../../../api/product";
import {getFileName} from "../../../utils/strUtils";

const productTypeOptions = getDictList("PRODUCT_TYPE")
const {theme, themeVars} = useTheme()
const token = Taro.getStorageSync('token')
const baseUrl = getBaseUrl()
const returnUrl = Api.fileUploadDynamicReturnUrl


const busiTypeList = ref([]);
const getProductCategoryPage = () => {
  twProductCategoryPage({current: 1, size: 1000, level: 1, status: 'ENABLE'}).then(res => {
    busiTypeList.value = res.data.records
  })
}
getProductCategoryPage()


const visible = ref(false)

const change = (value, pathNodes) => {
  formData.value.threeLevelCategoryName = toRaw(pathNodes[2]).text
  console.log(value)
  formData.value.oneLevelCategoryId = value[0]
  formData.value.twoLevelCategoryId = value[1]
  formData.value.threeLevelCategoryId = value[2]
}


const formData = ref({
  name: '',
  threeLevelCategoryName: '',
  price: '',
  specs: '',
  address: '',
  productType: '',
  detail: '',
  productImg: [],
  imgDesc: [],
  categoryArr: []
})

const formRef = ref(null)

const formRules = {
  threeLevelCategoryName: [{required: true, message: '请选择产品分类'},],
  productType: [{required: true, message: '请选择产品类型'},],
  name: [{required: true, message: '请输入商品名称'},],
  // price: [{required: true, message: '请输入商品价格'},],
  // specs: [{required: true, message: '请输入商品规格'},],
  productImg: [{required: true, message: '请上传产品图片'},
    {
      validator: (val) => {
        const list = toRaw(val)
        return new Promise((resolve, reject) => {
          if (list.length <= 0) {
            reject('请上传产品图片')
          } else {
            resolve('')
          }
        })
      }
    }],

}

const selectLocation = () => {
  console.log('selectLocation')

//获取位置
  Taro.getLocation({
    type: 'gcj02',
    altitude: true,
    isHighAccuracy: true,
    success: function (res) {
      Taro.chooseLocation({
        latitude: +res.latitude,
        longitude: +res.longitude,
        success(res) {
          console.log("chooseLocation", res)
          const {
            address,
            errMsg,
            latitude,
            longitude,
            name
          } = res
          // 根据经纬度获取省市区

        }
      })
    },
    fail: function (rr) {
      console.error("getLocation fail", rr)
      Taro.getSetting({
        success: res => {
          if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
            // 用户拒绝了授权
            Taro.showModal({
              title: '提示',
              content: '您拒绝了定位权限，将无法选择地址，修改位置消息',
              success: res => {
                console.log("showModal ", res)
                if (res.confirm) {
                  // 跳转设置页面
                  Taro.openSetting({
                    success: res => {
                      if (res.authSetting['scope.userLocation']) {
                        // 授权成功，重新定位
                        Taro.getLocation({
                          success: res => {

                            console.log("位置信息 ", res)
                          }
                        });
                      } else {
                        // 没有允许定位权限
                        Taro.showToast({
                          title: '您拒绝了定位权限，将无法选择地址，修改位置消息',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
          }
        }
      })
    }
  })
}

const reset = () => {
  formRef.value?.reset()
}

const submit = () => {
  console.log("111")
  formRef.value?.validate().then(({valid, errors}) => {
    if (valid) {
      console.log('success:', formData.value)
      const data = cloneDeep(formData.value)

      if (data.productImg.length > 0) {
        data.productImg = data.productImg.map(e => e.url).join(",")
      }
      if (data.imgDesc.length > 0) {
        data.imgDesc = data.imgDesc.map(e => e.url).join(",")
      } else {
        data.imgDesc = ""
      }
      console.log("data", data)
      twProductSubmitForm(data, !data.id).then(res => {
        if (res.code == 200) {
          /* Taro.showToast({title: res.msg, icon: 'success', duration: 1500,});
           Taro.navigateBack()*/
          auditHandle(res.data.id)
        }
      }).finally(()=>{
        Taro.hideLoading();
      })
    } else {
      console.warn('error:', errors)
    }
  })
}


const auditHandle = (e) => {

  console.log("确认提交审核", e)
  Taro.showLoading({
    title: '审核中',
  })
  twProductAudit({id: e}).then(res => {
    console.log("替身结果", res)
    if (200 == res.code) {
      Taro.navigateBack()
      Taro.showToast({title: res.msg, icon: 'none', duration: 1500,});
    }
  }).finally(() => {
    Taro.hideLoading()
  })
}


export default {
  components: {IconFont},

  // 可以使用所有的 Vue 生命周期方法
  mounted() {
  },

  onLoad(options) {
    console.log("aaaa load", options)
    formRef.value?.reset()
    formData.value = {
      name: '',
      threeLevelCategoryName: '',
      price: '',
      specs: '',
      address: '',
      productType: '',
      detail: '',
      productImg: [],
      imgDesc: [],
      categoryArr: []
    }
    if (options.id) {
      twProductMyDetail(options.id).then(res => {
        formData.value = res.data
        if (formData.value.productImg) {
          formData.value.productImg = res.data.productImg.split(',').map(url => {
            const img = {
              name: getFileName(url),
              url: url,
              status: 'success',
              message: '上传成功',
              type: 'image'
            }
            return img;
          })
        } else {
          formData.value.productImg = []
        }
        if (formData.value.imgDesc) {
          formData.value.imgDesc = res.data.imgDesc.split(',').map(url => {
            const img = {
              name: getFileName(url),
              url: url,
              status: 'success',
              message: '上传成功',
              type: 'image'
            }
            return img;
          })
        } else {
          formData.value.imgDesc = []
        }
        formData.value.categoryArr = [res.data.oneLevelCategoryId, res.data.twoLevelCategoryId, res.data.threeLevelCategoryId]

      })
    }
  },

  onReady() {
  },

  onShow() {
  },

  onHide() {
  },

  onPullDownRefresh() {
    console.log("onPullDownRefresh")
  },
  onReachBottom() {
    console.log("onReachBottom")
  },


  setup() {
    return {
      theme,
      themeVars,
      busiTypeList,
      formData,
      change,
      Taro,
      formRules,
      selectLocation,
      submit,
      baseUrl,
      returnUrl,
      productTypeOptions,
      visible,
      formRef,
      token
    }
  }
}

</script>

<style>


</style>